<template>
  <el-form-item>
   <div class="form-buttons">
     <el-button  @click="$router.go(-1)">返回</el-button>
      <el-button type="primary" @click="handleSubmit">修改</el-button>
    </div>
    </el-form-item>
<el-row justify="center" align="middle" style="height: 10vh;">
<el-col :span="10">
  <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="personal-info-form">
    <!-- ID 和 真实姓名 -->
    <el-row>
      <el-col :span="12">        
        <el-form-item label="ID" prop="id">
          <el-input v-model="form.id" placeholder="123" :disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="12">    
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="小明" :disabled="true" />
        </el-form-item>
      </el-col>
    </el-row>
    
    <!-- 用户角色 和 用户名称 -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="用户角色" prop="role">
          <el-input v-model="form.role" placeholder="用户" :disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" :disabled="true" />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 出生日期 和 性别 -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            v-model="form.birthDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 邮箱 -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-col>
    </el-row>
    <!--上传头像 -->
    <el-form-item label="头像" prop="avatar">
      <el-upload
        class="avatar-uploader"
        :show-file-list="true"
        :before-remove="beforeRemove"
        :before-upload="beforeAvatarUpload"
        :on-remove="handleRemove"
        name="file"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      
    </el-form-item> 
  </el-form>
</el-col>
</el-row>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useLoginStore } from "@/store/login";
import { searchUser, editUserInfo, downloadAvatar, updateUserInfo } from "@/api";
import { ElMessage ,dayjs} from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { fileToBase64 } from '@/utils/FileToBase64.js';
import { useHeaderStore } from '@/store/header';
import { storeToRefs } from 'pinia'

const loginStore = useLoginStore();
const headerStore = useHeaderStore()
const { userName,userImg } = storeToRefs(headerStore)
const formRef = ref(null);
const imageUrl = ref('');

const form = ref({
  id: '',
  realName: '',
  role: '',
  username: '',
  birthDate: '',
  gender: '',  
  email: '',
  avatar: '',
  file: ''
});

// 添加上传相关的配置
const baseURL = import.meta.env.VITE_API_BASE_URL || ''; // 从环境变量获取基础URL

// 上传请求头
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${localStorage.getItem('jwtToken')}`,
  'jwtToken': localStorage.getItem('jwtToken')
}));

// 获取头像的方法
const fetchAvatar = async (userId) => {
    try {
        const res = await downloadAvatar(userId);
        if (res.data) {
            const blob = new Blob([res.data]);
            imageUrl.value = URL.createObjectURL(blob);
        }
    } catch (error) {
        console.error('获取头像失败:', error);
    }
};

// 获取个人信息
const getUserInfo = async () => {
  try {
    const userId = loginStore.userInfo.data.userId;
    console.log('当前用户ID:', userId);
    
    const res = await searchUser({ userId });
    
    if (res.data.code === 200) {
      const userInfo = res.data.data;
      loginStore.setUserInfo(res.data);
      res.data.msg="登录成功"
      localStorage.setItem('userInfo',JSON.stringify(res.data))
      form.value = {
        id: userInfo.userId || '',
        realName: userInfo.name || '',
        role: userInfo.roleId === '1' ? '管理员' : '普通用户',
        username: userInfo.username || '',
        birthDate: dayjs(userInfo.birthday*1).format('YYYY-MM-DD') || '',
        gender: Number(userInfo.gender),
        email: userInfo.email || '',
        avatar: userInfo.avatar || '',
        file: '',
      };
     
      
      // 如果有头像，则下载头像
      if (userInfo.avatar) {
        await fetchAvatar(userId);
      }
    }
  } catch (error) {
    console.error('获取用户信息错误:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// 修改头像上传成功的处理方法
const handleAvatarSuccess = (response, file) => {
  imageUrl.value = URL.createObjectURL(file.raw);
  form.value.avatar = file.raw; // 保存文件对象而不是路径
};

// 修改头像上传前的验证
const beforeAvatarUpload = (file) => {
    // 验证文件类型和大小
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
        return false;
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
        return false;
    }

    // 添加预览
    imageUrl.value = URL.createObjectURL(file);
    form.value.file = file;
    
    return true;
};

// 移除文件的处理
const beforeRemove = (file) => {
    form.value.file = '';
    return true;
};

// 添加删除方法
const handleRemove = (file) => {
  ElMessageBox.confirm(
    '确定要删除这张图片吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      form.value.file = '';
      imageUrl.value = ''; // 清除预览图片
      ElMessage.success('删除成功');
    })
    .catch(() => {
      // 取消删除
    });
};

// 添加表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'change' },
    { min: 5, max: 20, message: '邮箱长度在 5 到 20 个字符', trigger: 'blur' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  gender: [
    { type: 'number', required: true, message: '请选择性别', trigger: 'blur' }
  ]
};

// 添加提交方法
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    
    // 转换生日为时间戳
    const birthday = form.value.birthDate ? new Date(form.value.birthDate).getTime() : null;
    console.log('生日时间戳:', birthday); // 调试用
    
    const submitData = {
      userId: form.value.id,
      name: form.value.realName,
      roleId: form.value.role === '管理员' ? '1' : '0',
      username: form.value.username,
      gender: form.value.gender,
      birthday: birthday, // 使用转换后的时间戳
      email: form.value.email,
      file: form.value.file
    };

    console.log('提交的数据:', submitData); // 调试用
    
    const res = await updateUserInfo(submitData);
    
    if (res.data.code === 200) {
      ElMessage.success('个人信息更新成功');
      userName.value= form.value.realName
      fileToBase64(form.value.file).then(res=>{
        // console.log(res);
          userImg.value=res//转换为base64
          getUserInfo();
    })

    } else {
      ElMessage.error(res.data.message || '更新失败');
    }
  } catch (error) {
    console.error('提交表单错误:', error);
    ElMessage.error('提交失败，请检查表单信息');
  }
};

onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
/* 定位按钮 */
.form-buttons {
position: absolute;
right: 100px;
display: flex;
}

.personal-info-form {
width: 100%;
max-width: 600px;
margin: 0 auto;
position: relative; 
}

.avatar-uploader {
display: inline-block;
}

.avatar {
width: 100px;
height: 100px;
border-radius: 50%;
object-fit: cover;
margin-top: 10px;
}

.avatar-uploader .avatar {
width: 200px;
height: 200px;
display: block;
}
.avatar-uploader .el-upload {
border: 2px solid #b3b3b3;
border-radius: 8px;
cursor: pointer;
position: relative;
overflow: hidden;
transition: all 0.3s ease; 
}

/* .avatar-uploader .el-upload:hover {
border-color: var(--el-color-primary); 
background-color: rgba(0, 0, 0, 0.05); 
} */

.el-icon.avatar-uploader-icon {
font-size: 40px;
border: 2px solid #ccc;
color: #8c939d;
width: 150px; 
height: 150px;
text-align: center;
line-height: 100px; 
}

.avatar-container img {
width: 100%;
height: 100%;
object-fit: cover;
}
.p{
color: #ccc;
padding-left: 100px;
}

</style>
